// @ts-nocheck
const { handleJson } = require("./common.js");
const { createResponse, handleError } = require("./common.js");
const Jsons = require("./jsonClass.js");
const jsonClass = new Jsons();
const fs = require("fs");
const recursiveMenu = (rawData, json, PATH) =>
  rawData.map((item) => {
    if (item.children) {
      if (item.path === PATH) {
        item.children.push(json);
      } else {
        recursiveMenu(item.children, json, PATH);
      }
    }
    return item;
  });
const addMenu = (rawData, json) => {
  const router = json.parent,
    type = json.menuType;

  delete json.parent;
  delete json.menuType;
  if (type === "目录") {
    json.children = [];
  }
  return router === "parent" ? [...rawData, json] : recursiveMenu(rawData, json, router);
};
const updateMenu = (rawData, json, type) => {};

module.exports = async (ctx) => {
  try {
    const data = ctx.request.body;
    const isNormal = jsonClass.handleCommon(ctx, `json/authMenuList.json`);
    if (isNormal) {
      const { jsonData, filePath, operation } = isNormal;
      let resultData = {};
      if (operation === "add") {
        resultData = createResponse(true, 200, "操作成功", addMenu(jsonData, data.json));
      } else if (operation === "update") {
        resultData = createResponse(true, 200, "操作成功", updateMenu(jsonData, data.json, data.type));
      }
      if (resultData.success) {
        jsonClass.writeFile(filePath, resultData.data);
        resultData.data = null;
      }
      ctx.body = resultData;
    }
  } catch (err) {
    handleError(ctx, err, "JSON操作");
  }
};
